﻿using SuperX.Common.Log;
using System;
using System.Collections.Generic;
using System.IO;
using System.Reflection;
using System.Text;

namespace SuperX.Common.Helper
{
    /// <summary>
    /// 反射帮助类
    /// </summary>
    public static class CreateInstanceUtil
    {
        // 
        public static List<string> GetDllPaths()
        {
            List<string> result;
            if ((result = CreateInstanceUtil._dllPaths) == null)
            {
                List<string> list = new List<string>() { "Libs" , "Drives" , "Services" };
                result = list;
                CreateInstanceUtil._dllPaths = list;
            }
            return result;
        }

        /// <summary>
        /// 创建对象实例
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="fullName">命名空间.类型名</param>
        /// <param name="assemblyName">程序集</param>
        /// <returns></returns>
        public static T CreateInstance<T>(string fullName, string assemblyName)
        {
            T result;
            try
            {
                string text = Path.Combine(Environment.CurrentDirectory, assemblyName);
                if (!File.Exists(text))
                {
                    foreach (string path in CreateInstanceUtil.GetDllPaths())
                    {
                        text = Path.Combine(Environment.CurrentDirectory, path, assemblyName);
                        if (File.Exists(text))
                        {
                            break;
                        }
                    }
                }
                if (!File.Exists(text))
                {
                    Logger.Error(string.Format("{0} 文件找不到", assemblyName));
                }
                result = (T)((object)Assembly.LoadFrom(text).CreateInstance(fullName));
            }
            catch (Exception exception)
            {
                Logger.ErrorException(exception);
                result = default;
            }
            return result;
        }

        // 
        public static T CreateInstance<T>(string assemblyName, string nameSpace, string className)
        {
            return CreateInstanceUtil.CreateInstance<T>(nameSpace + "." + className, assemblyName);
        }

        // 
        public static T CreateInstance<T>(string assemblyQualifiedName)
        {
            T result;
            try
            {
                string fullName = assemblyQualifiedName.Split(new char[]
                {
                    ','
                })[0];
                string assemblyName = assemblyQualifiedName.Split(new char[]
                {
                    ','
                })[1];
                result = CreateInstanceUtil.CreateInstance<T>(fullName, assemblyName);
            }
            catch (Exception)
            {
                result = default;
            }
            return result;
        }

        // 
        private static List<string> _dllPaths;
    }
}
